<?php
/**
 * User: hujingdong
 * Date: 2022-02-18
 * Time: 11:27
 */

namespace Frieza\Modules\DingDing\Controllers;

use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use function AlibabaCloud\Client\json;

class IndexController
{
    const DEFAULT_URL = "admin/linkselect/getlink?url=/admin/";

    public function index(Request $request, Content $content)
    {
        $content->header('生成钉钉跳转页面链接')->description(' ');

        $form = new Form();
        $form->text("link", "输入需要生成的链接");
        $form->textarea('ding_link', '钉钉链接');
        //$form->action('/admin/getDingLink');

        //script
        $script = <<<EOT
(function () {
	$(':input[name="link"]').on('blur', function () {
	    var link = this.value;
	    if(link != ''){
        $.ajax({
            url:"/admin/DingDing/getDingLink",
            type:"GET",
            data:{link : link},
            dataType:"json",
            success:function(result){
                if (result.ding_link.length > 0) {
                    $(':input[name="ding_link"]').val(result.ding_link);
                }
            }
        });
       }
	});
})();
EOT;
        Admin::script($script);

        $form->disableReset();
        $form->disableSubmit();

        $content->row($form);
        return $content;
    }

    public function getDingLink(Request $request){
        $link = $request->input('link', '');
        //获取要跳转的链接
        $link_arr = explode("admin/",$link);
        $domain_name = $link_arr[0];
        $redirect_url = $link_arr[1];
        //对跳转链接的参数进行json_encode加密
        $params_arr = explode("?",$redirect_url);
        $redirect_url_result = $redirect_url;
        if (!empty($params_arr[1])){
            //对参数进行json_encode
            $params = base64_encode($params_arr[1]);
            $redirect_arr = [$params_arr[0],$params];
            $redirect_url_result = implode("?",$redirect_arr);
        }

        //拼接完整链接
        $ding_link = $domain_name.self::DEFAULT_URL.$redirect_url_result;
        return response()->json(compact('ding_link', 'link'));
    }


}